/**
 * 
 */
package thread;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author xyyi
 *
 *http://tutorials.jenkov.com/java-concurrency/blocking-queues.html
 */
public class BlockingQueue<E> {

	Queue<E> queue = new LinkedList<E>();
	int limit = 0;

	/**
	 * 
	 */
	public BlockingQueue(int limit) {
		this.limit = limit;
	}

	public synchronized void enque(E e) throws InterruptedException {
		while (this.queue.size() == this.limit) {
			wait();
		}

		if (queue.size() == 0) {
			notifyAll();
		}

		queue.offer(e);
	}

	public synchronized E deque() throws InterruptedException {
		while (this.queue.size() == 0) {
			wait();
		}

		if (this.queue.size() == this.limit) {
			notifyAll();
		}

		return queue.poll();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
